<?php
/**
 * Created by chency.
 * User: Administrator
 * Date: 2018/11/4 0004
 * Time: 下午 6:12
 */

namespace app\admin\model;

use think\Model;
use think\cache\driver\Redis;

class ProductModel extends Model
{
    public $table = 'tps_product';

    private $cacheListName = 'PRODUCT_CACHE_LIST';

    private $cacheDetailName = 'PRODUCT_CACHE_DETAIL';

    /**
     * 获取列表1
     * @param $map
     * @param $page
     * @param int $listRows
     * @return array|mixed|null|string|\think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList ($map, $page, $listRows = 5)
    {
        $list = $this
            ->field ('p.id,p.name,p.pic_id,p.add_time AS create_time,p.update_time,p.status,pt.name AS type_name,p.price')
            ->join ('tps_product_type pt', 'pt.id = p.type', 'left')
            ->alias ('p')
            ->where ($map)
            ->order ('p.add_time DESC')
            ->paginate ($listRows);
        return $list;
    }

    /**
     * 获取单条
     * @param $map
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDetails ($map)
    {
        $redis = new Redis();
        $redis->rm($this->cacheListName);
        $redis->rm($this->cacheDetailName);
        $detail = $this
            ->field ('p.id,p.name,p.pic_id,p.add_time AS create_time,p.update_time,p.status,pt.name AS type_name,pic.url AS pic,p.type,ni.description,ni.content,p.price')
            ->join ('tps_product_type pt', 'pt.id = p.type', 'left')
            ->join ('tps_picture pic', 'pic.id = p.pic_id', 'left')
            ->join ('tps_news ni', 'ni.id = p.introduce_id', 'left')
            ->alias ('p')
            ->where ($map)
            ->find ();
        //获取上一条 和下一条
        $detail['next_id'] = $this->where (['add_time' => ['lt', $detail['create_time']], 'type' => $detail['type']])->order ('add_time DESC')->value ('id');
        $detail['pre_id'] = $this->where (['add_time' => ['gt', $detail['create_time']], 'type' => $detail['type']])->order ('add_time ASC')->value ('id');
        return $detail;
    }

    public function saveDetails ($map, $data)
    {
        if (empty($map)) $oldDetails = [];
        else            $oldDetails = $this->getDetails ($map);
        if (empty($oldDetails)) {
            $res = $this->add ($data);
        } else {
            $res = $this->where ($map)->save ($data);
        }
        return $res;
    }
}